package usercenter

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"navi-mumbai/common/gensql"
	"time"
)

var _ UserLoginStatModel = (*customUserLoginStatModel)(nil)

type (
	// UserLoginStatModel is an interface to be customized, add more methods here,
	// and implement the added methods in customUserLoginStatModel.
	UserLoginStatModel interface {
		userLoginStatModel
		InsertTrans(ctx context.Context, tx sqlx.Session, data *UserLoginStat) (sql.Result, error)
		CountLoginUser(ctx context.Context, start, end *time.Time) (int64, error)
	}

	customUserLoginStatModel struct {
		*defaultUserLoginStatModel
		genSql *gensql.GenSql
	}
)

// NewUserLoginStatModel returns a model for the database table.
func NewUserLoginStatModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserLoginStatModel {
	return &customUserLoginStatModel{
		defaultUserLoginStatModel: newUserLoginStatModel(conn, c, opts...),
		genSql:                    gensql.NewGenSql(),
	}
}

func (m *customUserLoginStatModel) InsertTrans(ctx context.Context, tx sqlx.Session, data *UserLoginStat) (sql.Result, error) {
	mumbaiUserLoginStatUidKey := fmt.Sprintf("%s%v", cacheMumbaiUsercenterUserLoginStatUidPrefix, data.Uid)
	ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, userLoginStatRowsExpectAutoSet)
		return tx.ExecCtx(ctx, query, data.Uid, data.LoginTime, data.TodayLoginCnt, data.LoginCntSum, data.AppVer, data.LoginIp, data.LoginDevice, data.LoginDeviceId, data.LoginDays)
	}, mumbaiUserLoginStatUidKey)
	return ret, err
}

func (m *customUserLoginStatModel) CountLoginUser(ctx context.Context, start, end *time.Time) (int64, error) {
	q := fmt.Sprintf("select count(uid) from %s ", m.table)
	m.genSql.InitSql(q)
	if start != nil {
		m.genSql = m.genSql.Where("login_time >= ?", start)
	}
	if end != nil {
		m.genSql = m.genSql.Where("login_time <= ?", end)
	}

	query, values, err := m.genSql.ToSql()
	if err != nil {
		return 0, err
	}
	var resp int64
	err = m.QueryRowNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return 0, err
	}
}
